import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { ElMessage } from 'element-plus'
import router from './router';
import buildRoute from './router/buildRoute';
import { WHITE_LIST } from '@/router';
import { getToken } from './utils/user';
import { getUrlValue } from './utils/index';
import { logout, setToken } from '@/utils/user';
import { acceptToken } from '@/api/user';

NProgress.configure({ showSpinner: false });

let dataFlag = false; // 标识：是否为第一次进入系统

const backUrl = getUrlValue()
let codeValue = backUrl.code
// code检测和请求登录
const login = async () => {
  if (codeValue.indexOf('#') != -1) {
    codeValue = codeValue.split('#')[0]
  }
  const params = {
    redirect_uri: 'http://10.121.113.19:5173',
    code: codeValue
  }
  acceptToken(params).then(async (res: any) => {
    setToken(res.data.accessToken);
    await buildRoute();
    router.push('/');
  })
  .catch((err: any) => {
    ElMessage.error(err.msg);
  })
}

router.beforeEach(async (to: any, from: any, next) => {
  NProgress.start();
  // 白名单路由直接进入
  if (WHITE_LIST.includes(to.path)) {
    NProgress.done();
    next();
    return true;
  }
  if (!dataFlag) {
    dataFlag = true;
    const accessToken = getToken() as string;
    if (accessToken) {
      await buildRoute();
      NProgress.done();
    } else {
      // logout();
      NProgress.done();
      if (codeValue) {
        login()
      } else {
        window.location.href = 'https://ziam.chintcloud.net/api/uiac/auth/oauth/authorize?client_id=web-template&response_type=code&redirect_uri=http://10.121.113.19:5173'
        return false;
      }
    }
    next({ ...to, replace: true });
  } else {
    NProgress.done();
    next();
  }
});
